# -*- coding: utf-8 -*-
########################################################################
#
# (c) 2010-2011 Markus Dittrich
#
# This program is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public
# License Version 3 as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License Version 3 for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the Free
# Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
#
#######################################################################

import os

from PyQt4.QtCore import QDir
from sqlite3 import *
from datetime import date, time



def create_calendar(calendar):

    start = date(2010, 8, 19)
    aTime  = "13:00:00"
    calendar.add_event(start, aTime, 30, "cool stuff", "we will be doing cool stuff")

    start = date(2010, 8, 20)
    aTime  = "8:00:00"
    calendar.add_event(start, aTime, 60, "early stuff", "we will be doing early stuff")



def event_date(event):
    """ Extracts and returns the date of a single event. """
    
    return event[1]



def event_time(event):
    """ Extracts and returns the time of a single event. """
    
    return event[2]



def event_duration(event):
    """ Extracts and returns the duration of a single event. """
    
    return event[3]



def event_title(event):
    """ Extracts and returns the title of a single event. """
    
    return event[4]



def event_description(event):
    """ Extracts and returns the description of a single event. """
    
    return event[5]



def row_to_events(row):
    """ Converts a raw database entry (row) to an event dictionary. """

    newEvent = {}
    newEvent["title"]       = event_title(row)
    newEvent["description"] = event_description(row)
    newEvent["duration"]    = event_duration(row)
    newEvent["time"]        = event_time(row)
    newEvent["date"]        = event_date(row)

    return newEvent



def to_events(cursor):
    """ Converts a cursor returned by sqlite into a
    list of events.

    """

    allEvents = []
    for row in cursor:
        allEvents.append(row_to_events(row))

    return allEvents




class CalendarStorage(object):
    """ Main calendar database object. """

    dataBaseDirectory = ".caliente"
    dataBaseName = "caliente.db"

    def __init__(self, path):
        """
        We either create a brand new database if this is the
        first time we're called, otherwise we open an already
        existing one.
        """

        calendarPath = os.path.join(str(path), self.dataBaseDirectory)
        calendarFile = os.path.join(calendarPath, self.dataBaseName)

        if not os.path.exists(calendarFile):

            # need to make sure we create the directory
            # before asking sqlite to create the database file
            if not os.path.exists(calendarPath):
                os.mkdir(calendarPath, 0700)

            self._db = connect(calendarFile)
            cursor    = self._db.cursor()
            cursor.execute("create table calendar (id integer primary key," 
                           "eventDate date, eventTime time, duration integer,"
                           "title text, descr text)")
        else:
            self._db = connect(calendarFile)



    def add_event(self, startDate, startTime, duration, title, description):
        """
        Add a single event to the calendar database.
        """

        cursor = self._db.cursor()
        cursor.execute("insert into calendar values (?,?,?,?,?,?)", (None, \
                startDate, startTime, 10, title, description))
        self._db.commit()



    def delete_event(self, eventID):
        """
        Delete the event with eventID.
        """

        cursor = self._db.cursor()
        cursor.execute("delete from calendar where id = ?", (eventID,))
        self._db.commit()



    def get_event_by_id(self, eventID):
        """
        Return the event corresponding to the specified event ID if it
        exists. This is either a single event or none.
        """
      
        cursor = self._db.cursor()
        event = cursor.execute("select * from calendar where " \
                "id = ?", (eventID,))

        return to_events(event)



    def get_events_by_date(self, date):
        """
        Return all events present for the given day if any. This
        could in principle be any number of events.
        """

        cursor = self._db.cursor()
        eventCursor = cursor.execute("select * from calendar where "\
                                     "eventDate = ?", (date,))

        return to_events(eventCursor)



    def get_all_events(self):
        """
        Return all events currently in the database.
        """

        cursor = self._db.cursor()
        cursor.execute("select * from calendar")
        
        return to_events(cursor)



    def change_event(self, eventId, newDate = None, newTime = None,
            newTitle =None, newDescription = None):
        """
        Changes the properties of the event with the given eventID.
        The value of all properties which are not None will be changed.
        """
        
        cursor = self._db.cursor()

        if newDate:
            cursor.execute("update calendar set eventDate = ? where " \
                    "id = ?", (newData, eventId))

        if newTime:
            cursor.execute("update calendar set eventTime = ? where " \
                    "id = ?", (newTime, eventId))

        if newTitle:
            cursor.execute("update calendar set title = ? where " \
                    "id = ?", (newTitle, eventId))

        if newDescription:
            cursor.execute("update calendar set descr = ? where " \
                    "id = ?", (newDescription, eventId))

        self._db.commit()        



    def print_content(self):

        cursor = self._db.cursor()
        foo = cursor.execute("select * from calendar")
        for row in cursor:
            print(row)


